#include "ff_port.h"
#include "drv_spi_w25qxx.h"
#include "loger.h"


/* fatfs - SD卡接口 */

/* define */

#define TAG "FS-FLS"

#define FLS_SECTOR_SIZE   512
#define FLS_SECTOR_COUNT  7424 * 2    /* 25Q128,最后7424KB字节给FATFS占用 */
#define FLS_BLOCK_SIZE    8           /* 每个BLOCK有8个扇区 */
#define FLS_FATFS_BASE    2240*4096   /* FATFS在外部FLASH的起始地址 */


/* static func */



static DSTATUS fls_init(void)
{
    return 0;
}

static DSTATUS fls_deinit(void)
{
    return 0;
}

static DSTATUS fls_status(void)
{
    return 0;
}

static DRESULT fls_read(BYTE *buff, DWORD sector, UINT count)
{
    for (; count > 0; count--)
    {
        drv_spi_w25qxx_read(FLS_FATFS_BASE+sector*FLS_SECTOR_SIZE, (uint8_t*)buff, FLS_SECTOR_SIZE);
        sector++;
        buff += FLS_SECTOR_SIZE;
    }
    return RES_OK;
}

static DRESULT fls_write(const BYTE *buff, DWORD sector, UINT count)
{
    for (; count > 0; count--)
    {
        drv_spi_w25qxx_write(FLS_FATFS_BASE+sector*FLS_SECTOR_SIZE, (uint8_t*)buff, FLS_SECTOR_SIZE);
        sector++;
        buff += FLS_SECTOR_SIZE;
    }

    return RES_OK;
}

static DRESULT fls_ioctl(BYTE cmd, void *buff)
{
    DRESULT res = RES_OK;

    switch (cmd)
    {
    case CTRL_SYNC:
        break;
    case GET_SECTOR_COUNT:
        *(DWORD *)buff = FLS_SECTOR_COUNT;
        break;
    case GET_SECTOR_SIZE:
        *(DWORD *)buff = FLS_SECTOR_SIZE;
        break;
    case GET_BLOCK_SIZE:
        *(DWORD *)buff = FLS_BLOCK_SIZE;
        break;
    default:
        res = RES_PARERR;
        break;
    }

    return res;
}

/* export */

const _ff_port_opt_t ff_port_fls = 
{
    .name = "fls",
    .init = fls_init,
    .deinit = fls_deinit,
    .status = fls_status,
    .read = fls_read,
    .write = fls_write,
    .ioctl = fls_ioctl,
};

